import React, { useEffect } from 'react'

// 懒加载通用方法：图片 + dom
function lazyload () {
    setTimeout(()=>{
        let dom = document.getElementById("lazyload")

        if(dom.className.indexOf("lazyimg") === -1){
            dom.className = dom.className + " lazyimg";
        }
    }, 20)

    // 要考虑兼容移动端
    // const event = "undefined" != typeof document && "function" != typeof document ? "touchmove touchend scroll" : "scroll"
    window.addEventListener("scroll", e => {
        console.log(e.target)

        let imgs = document.getElementsByTagName("img")
        toArray(imgs).map(img => {
            // console.log(img.offsetTop)
            let r = img.offsetTop
            let o = window.innerHeight || window.screen.height;
            if(window.pageYOffset > r + o || window.pageYOffset < r - o && "done" != img.getAttribute("data-src")){
                // clearTimeout(i)
            } else if(window.pageYOffset > r - o && "done" != img.getAttribute("data-src")){
                // n(e, this)

                const url = img.getAttribute("data-src")
                img.setAttribute("data-src", "done")
                img.setAttribute("src", url)
            }
            // return  ? void clearTimeout(i) : void ()
        })
    })
}

function toArray (array) {
    return Array.prototype.slice.call(array)
}

function ImgLazyload() {
    const imgUrl = "//gw.alicdn.com/bao/uploaded/i2/2644294448/O1CN01t979PX1ijEPHPCpke_!!2644294448.jpg_500x500q90.jpg_.webp"
    let i = 0
    const render = () => {
        const dom = []
        while(i<50){
            dom.push(<li key={i}><p><img width="80px" data-src={imgUrl} /></p></li>)
            i++
        }

        return dom.map(element => element)
    }


    useEffect(() => {
        lazyload()
    }, [])

    return (
        <div>
            <ul id="lazyload" className="lazyload">
                {render()}
            </ul>
        </div>
    )
}

export default ImgLazyload
